package com.atguigu.juc.day01.create;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class Demo04Future {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // 1、创建 Callable 类型的对象
        Callable<String> callable = () -> {

            TimeUnit.SECONDS.sleep(10);

            return "task result";
        };

        // 2、创建 FutureTask 对象
        FutureTask<String> futureTask = new FutureTask<>(callable);

        // 3、创建 Thread 对象并启动线程
        new Thread(futureTask).start();

        // 4、判断任务是否结束
        boolean isDone = futureTask.isDone();
        System.out.println("isDone = " + isDone);

        // ※主线程等待 3 秒之后，尝试取消目标任务
        TimeUnit.SECONDS.sleep(3);
        futureTask.cancel(true);

        // ※判断任务取消是否成功
        boolean cancelled = futureTask.isCancelled();
        System.out.println("cancelled = " + cancelled);

        // 5、打印任务结果
        // ※对于一个已经取消的任务调用 get() 方法获取结果，会抛异常：
        // Exception in thread "main" java.util.concurrent.CancellationException
        String taskResult = futureTask.get();
        System.out.println("taskResult = " + taskResult);

        isDone = futureTask.isDone();
        System.out.println("isDone = " + isDone);

    }

}
